package com.xuwei.chatroom.controller;

import com.xuwei.chatroom.entity.Message;
import com.xuwei.chatroom.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @Author xuwei
 * @Date 2020/8/9 21:47
 * @Description 主页面
 */
@Controller
@Slf4j
public class mainController {

    @Resource
    private ServletContext servletContext;

    /**
     * 首页跳转
     */
    @GetMapping({"/", "/main"})
    public String main() {
        return "/main";
    }

    /**
     * 检测用户的Session是否存活
     *
     * @return 检测结果
     */
    @GetMapping("/user/check")
    public ResponseEntity<Boolean> checkUser(HttpServletRequest request) {
        //从session中获取用户信息
        User user = (User) request.getSession().getAttribute("USER");
        //判断用户session是否过期
        if (user == null) {
            //登录信息已过期
            return ResponseEntity.ok(true);
        }
        log.info("检测用户{}的Session是否过期", user.getUsername());
        return ResponseEntity.ok(false);
    }

    /**
     * 踢出用户
     *
     * @param id 用户ID
     * @return 处理结果
     */
    @GetMapping("/user/kick")
    public ResponseEntity<String> kickOutUser(Integer id) {
        log.info("踢出用户:用户id:{}", id);
        Map<User, HttpSession> userMap = (Map<User, HttpSession>) servletContext.getAttribute("userMap");
        User user = new User();
        user.setId(id);
        //根据ID获取用户的session
        HttpSession session = userMap.get(user);
        if (session == null) {
            return ResponseEntity.badRequest().body("踢人失败，该用户不存在或已下线！");
        }
        //销毁该用户的session
        session.invalidate();
        return ResponseEntity.ok("踢出成功！");
    }

    /**
     * 获取在线人员列表
     */
    @GetMapping("/online")
    public String online() {
        log.info("获取在线人员列表！");
        return "common::online";
    }



    /**
     * 获取聊天内容
     */
    @GetMapping("/user/getMessage")
    public ResponseEntity<String> getMessage() {
        String message = (String) servletContext.getAttribute("message");
        if (StringUtils.isEmpty(message)) {
            return ResponseEntity.badRequest().body("聊天信息不存在");
        }
        return ResponseEntity.ok(message);
    }

    /**
     * 发送消息
     */
    @PostMapping("/user/sendMessage")
    public ResponseEntity<String> sendMessage(@RequestBody Message message) {
        log.info("{}发送消息给{}:{}", message.getFrom(), message.getTo(), message.getContent());
        // 发言时间
        message.setSendTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 获得ServletContext的sourceMessage对象.
        String sourceMessage = (String) servletContext.getAttribute("message");
        //封装消息
        StringBuffer sb = new StringBuffer(sourceMessage);
        sb.append("<font color='blue'><strong>")
                .append(message.getFrom())
                .append("</strong></font><font color='#CC0000'>")
                .append(message.getFace())
                .append("</font>对<font color='green'>[")
                .append(message.getTo())
                .append("]</font>说：<font color='")
                .append(message.getColor())
                .append("'>")
                .append(message.getContent())
                .append("</font>（")
                .append(message.getSendTime())
                .append("）<br>");
        servletContext.setAttribute("message", sb.toString());
        return ResponseEntity.ok("发送成功");
    }
}
